﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Net;

namespace ScreenTranslate
{
    public class StudentNet
    {
        private string ipaddress = "192.168.3.4";
        private int port = 1237;
        private Form1 student;
        private Socket socket;
        private IPEndPoint ipendPoint;
        private Message message;

        public StudentNet(string ipaddress,Form1 student)
        {
            this.ipaddress = string.IsNullOrEmpty(ipaddress) ? "127.0.0.1" : ipaddress;
            this.student = student;
            message = new Message();
            ipendPoint = new IPEndPoint(IPAddress.Parse(this.ipaddress),port);
        }

        public void Start()
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipendPoint);
                BeginReceive();
            }catch(Exception e)
            {

            }
        }

        /// <summary>
        /// 异步消息接收
        /// </summary>
        private void BeginReceive()
        {
            socket.BeginReceive(message.Data, message.StartIndex, message.RemainSize, SocketFlags.None, ReceiveCallback, null);
        }

        /// <summary>
        /// 收到消息处理
        /// </summary>
        /// <param name="ar"></param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                if (socket == null || socket.Connected == false)
                    return;

                int count = socket.EndReceive(ar);
                //解析消息
                message.ReadMessage(count, OnProcessDataCallback);
                //继续接收消息
                BeginReceive();

            }
            catch (Exception e)
            {
               
            }
        }

        //消息回调处理
        private void OnProcessDataCallback(byte[] bytes)
        {
            student.SetImage(bytes);
        }

        public void Close()
        {
            if(socket != null)
            {
                socket.Close();
            }
        }
    }
}
